/**
 * Copyright (c) 2011-2014, hubin (243194995@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.founder.client;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

 
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.SSOToken;
 
public class IndexServlet extends HttpServlet {

	private static final long serialVersionUID = 3943268102235933441L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		try {
			String returnUrl = ReturnUrlUtil.getAhfzbdReturnUrl(request);
			SSOToken token = SSOHelper.getToken(request);
			if (WebUtilsPro.isAjaxRequest(request)) {
				if (token == null) {
					/**
					 * 重定向至代理跨域地址页
					 */
					Map map = new HashMap();
					map.put("userId", null);
					map.put("data", null);
					map.put("loginUrl", UrlConstant.URL_LOGIN + "?ReturnURL="
							+ returnUrl + "proxylogin.html");
					AjaxHelper.jsonPrint(response, map, "UTF-8");
				} else {

					Map map = new HashMap();
					map.put("userId", token.getUid());
					map.put("data", token.getData());
					AjaxHelper.jsonPrint(response, map, "UTF-8");
				}
			} else {
				if (token == null) {
					/**
					 * 重定向至代理跨域地址页
					 */
					response.sendRedirect(UrlConstant.URL_LOGIN + "?ReturnURL="
							+ returnUrl + "/proxylogin.html");
				} else {
					String index = request.getParameter("index");
					index = index == null ? "index.jsp" : index;
					/*
					request.setAttribute("userId", token.getUid());
					request.setAttribute("data", token.getData());
					 request.getRequestDispatcher("/" + index).forward(request,
							response);*/
					HttpSession session =   request.getSession();
					session.setAttribute("userId", token.getUid());
					session.setAttribute("data", token.getData());
					response.sendRedirect(ReturnUrlUtil.getAhfzbdUrl(request)+"/"+index);

				}
			}

		} catch (Throwable e) {

			e.printStackTrace();
			response.sendRedirect(UrlConstant.URL_LOGIN);
		}
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}
}